package com.agileboot.admin.controller.common;

import com.agileboot.common.core.dto.ResponseDTO;
import com.agileboot.domain.common.dto.UploadDTO;
import com.agileboot.domain.system.file.FileApplicationService;
import com.agileboot.domain.system.file.db.SysFileEntity;
import com.agileboot.infrastructure.user.AuthenticationUtils;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
@RequestMapping("/qiNiufile")
@RequiredArgsConstructor
public class QiniuFileController {

    private final QiniuService qiniuService = new QiniuService();
    private final FileApplicationService fileApplicationService;

    @Operation(summary = "七牛云文件上传")
    @PostMapping("/uploadToQiniu")
    public ResponseDTO<UploadDTO> uploadToQiniu(@RequestParam("file") MultipartFile file,
                                                @RequestParam(value = "bizType", required = false) String bizType,
                                                @RequestParam(value = "bizId", required = false) Long bizId) {
        try {
            if (file == null || file.isEmpty()) {
                throw new RuntimeException("上传文件为空");
            }

            // 获取七牛云上传凭证
            String uploadToken = qiniuService.getUploadToken();

            // 创建配置类和上传管理器
            Configuration cfg = new Configuration(Region.autoRegion());
            UploadManager uploadManager = new UploadManager(cfg);

            // 文件上传到七牛云
            String fileName = file.getOriginalFilename();
            String key = StringUtils.cleanPath(fileName); // 或者你可以设置自定义的文件名

            // 上传
            Response response = uploadManager.put(file.getInputStream(), key, uploadToken, null, null);

            // 解析上传结果
            DefaultPutRet putRet = response.jsonToObject(DefaultPutRet.class);
            String fileUrl = "http://cloud-file.dingyangmy.cn/" + putRet.key;

            // 构建UploadDTO对象，保持与FileController一致的格式
            UploadDTO uploadDTO = UploadDTO.builder()
                    .url(fileUrl)
                    .fileName(putRet.key)
                    .newFileName(key)
                    .originalFilename(fileName)
                    .build();

            // 保存文件信息到数据库
            try {
                SysFileEntity fileEntity = new SysFileEntity();
                fileEntity.setFileName(fileName);
                fileEntity.setFileKey(putRet.key);
                // 提取文件后缀
                if (fileName != null && fileName.contains(".")) {
                    fileEntity.setFileSuffix(fileName.substring(fileName.lastIndexOf(".") + 1));
                }
                fileEntity.setFileType(file.getContentType());
                fileEntity.setFileSize(file.getSize());
                fileEntity.setStorageType("qiniu");
                fileEntity.setUrl(fileUrl);
                fileEntity.setBizType(bizType);
                fileEntity.setBizId(bizId);
                
                // 尝试获取当前登录用户ID，如果未登录则为null
                try {
                    Long userId = AuthenticationUtils.getUserId();
                    fileEntity.setCreatorId(userId);
                } catch (Exception e) {
                    // 未登录时忽略，creatorId保持为null
                    log.debug("未获取到登录用户信息，文件记录的creatorId为null");
                }
                
                fileApplicationService.saveFileInfo(fileEntity);
                log.info("文件信息已保存到数据库，fileId: {}", fileEntity.getFileId());
            } catch (Exception e) {
                // 保存文件信息失败不影响上传结果，只记录日志
                log.error("保存文件信息到数据库失败", e);
            }

            return ResponseDTO.ok(uploadDTO);

        } catch (Exception e) {
            log.error("七牛云文件上传失败", e);
            throw new RuntimeException("上传失败：" + e.getMessage());
        }
    }
}